// 第一题
// 求数组中连续n项点最大和
// [2, 5, 3, 4, 6]  2 =》 10
// [2, 5, 3, 4, 6]  3 => 13



// 方法一:截取数组的求和

function sum(arr) {
    return arr.reduce((pre, nxt) => {
        return pre + nxt;
    })
}

function getMaxSum(arr, n) {
    let left = 0;
    let right = left + n;
    let max = sum(arr.slice(left, right));
    for(;right <= arr.length; left++, right++) {
        tempSum = sum(arr.slice(left, right));
        if (tempSum > max) {
            max = tempSum;
        }
    };
    return max;
};
let arr1 = [2, 5, 3, 4, 6];
// console.log(getMaxSum(arr1, 2));




// 方法二: 算法思路

function getMaxSum2(arr, n) {
    let max = 0;
    let preSum = 0;
    for (let i = 0; i < arr.length; i++) {
        if (i === 0) {
            for(let j = 0; j< n; j++) {
                max += arr[j];
            }
            preSum = max;
        } else {
            const temp = preSum - arr[i - 1] + arr[i - 1 + n];
            if (temp > max) {
                max = temp;
            };
            preSum = temp;
        }
    }
    return max;
}
console.log(getMaxSum2(arr1, 3));